<?php

Yii::import('common.models._base.BaseMakeQuery');

class MakeQuery extends BaseMakeQuery {

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function rules() {
        return array(
            array('name, query', 'required'),
            array('users_id', 'numerical', 'integerOnly' => true),
            array('name, email', 'length', 'max' => 45),
            array('email+classes_id', 'common.extensions.uniqueMultiColumnValidator', 'caseSensitive' => true, 'message' => 'you have already made a query for this class.'),
            array('email+courses_id', 'common.extensions.uniqueMultiColumnValidator', 'caseSensitive' => true, 'message' => 'you have already made a query for this course.'),
            array('phone', 'match', 'pattern' => '/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/'),
            array('classes_id, courses_id', 'length', 'max' => 20),
            array('phone, classes_id, courses_id', 'default', 'setOnEmpty' => true, 'value' => null),
            array('id, name, email, phone, query, users_id, classes_id, courses_id, created_by, is_converted,mail_sent,backend_user_id', 'safe'),
            array('id, name, email, phone, query, users_id, classes_id, courses_id', 'safe', 'on' => 'search'),
        );
    }

    public static function getConvertedQuery($classId) {
        $makeQuery = MakeQuery::model()->findAllByAttributes(array('classes_id' => $classId));
        return $makeQuery;
    }

    public static function getConvertedCourseQuery($courseId) {
        $makeQuery = MakeQuery::model()->findAllByAttributes(array('courses_id' => $courseId));
        return $makeQuery;
    }

    public static function mailToTrainerreminderLink($data) {
        if ($data->classes_id != '') {
            $classCourse = getClaCourseInfo('Classes', $data->classes_id);
        }
        if ($data->courses_id != '') {
            $classCourse = getClaCourseInfo('Courses', $data->courses_id);
        }
        if ($classCourse->users_id != '') {
            $classId = ($data->classes_id != '') ? $data->classes_id : '0';
            $courseId = ($data->courses_id != '') ? $data->courses_id : '0';
            return CHtml::link("Remind To Trainer", "javascript:void(0);", array("onclick" => "remindtoTrainer($classId,$courseId,$data->id)"));
        }
    }

    public static function getTrainerName($data) {
        if ($data->classes_id != '') {
            $classCourse = getClaCourseInfo('Classes', $data->classes_id);
            $usersdetails = ($classCourse->users_id != '') ? Users::getFrontEndUser($classCourse->users_id) : Users::getBackEndUser($classCourse->backend_user_id);
            return $usersdetails->first_name . ' ' . $usersdetails->last_name;
        }
        if ($data->courses_id != '') {
            $classCourse = getClaCourseInfo('Courses', $data->courses_id);
            $usersdetails = ($classCourse->users_id != '') ? Users::getFrontEndUser($classCourse->users_id) : Users::getBackEndUser($classCourse->backend_user_id);
            return $usersdetails->first_name . ' ' . $usersdetails->last_name;
        }
    }

    public static function classCoursename($data) {
        if ($data->classes_id != '') {
            $classCourse = getClaCourseInfo('Classes', $data->classes_id);
            return '<b>Class Name:</b> ' . $classCourse->class_titile;
        }
        if ($data->courses_id != '') {
            $classCourse = getClaCourseInfo('Courses', $data->courses_id);
            return '<b>Course Name:</b> ' . $classCourse->course_titile;
        }
    }

    public function search() {
        $criteria = new CDbCriteria;
        $criteria->compare('id', $this->id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('phone', $this->phone, true);
        $criteria->compare('query', $this->query, true);
        $criteria->compare('users_id', $this->users_id);
        $criteria->compare('classes_id', $this->classes_id);
        $criteria->compare('courses_id', $this->courses_id);
        $criteria->compare('is_converted', ($this->is_converted == 'null') ? null : $this->is_converted, true);
        $criteria->compare('created', $this->created, true);
        $criteria->compare('created_by', $this->created_by);
        $criteria->compare('mail_sent', $this->mail_sent);
        $criteria->compare('backend_user_id', $this->backend_user_id);
        $criteria->order = 'created DESC';

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }
    
    
    

    public static function trainerResponseRate($frontUser, $backUser) {
        if (!empty($frontUser)) {
            $userId = $frontUser;
            $fieldName = 'created_by';
        }
        if (!empty($backUser)) {
            $userId = $backUser;
            $fieldName = 'backend_user_id';
        }
        $totalQuery = MakeQuery::model()->countByAttributes(array($fieldName => $userId));
        $totalReplyQuery = MakeQuery::model()->countByAttributes(array($fieldName => $userId, 'mail_sent' => SkillConfig::STATUS_ACTIVE));
        if ($totalReplyQuery >= 1 && $totalQuery >= 1) {
            $reponse = ($totalReplyQuery / $totalQuery) * 100;
            return ceil($reponse);
        }
    }

    public static function getClassConvertedUser($classId) {
        $userdetails = MakeQuery::model()->findAll('classes_id=' . $classId . ' AND is_converted=' . SkillConfig::STATUS_ACTIVE);
        return $userdetails;
    }

    public static function getCourseConvertedUser($coursesId) {
        $userdetails = MakeQuery::model()->findAll('courses_id=' . $coursesId . ' AND is_converted=' . SkillConfig::STATUS_ACTIVE);
        return $userdetails;
    }

    public static function counttotalQuery($id, $type) {
        $classCoursetype = ($type != SkillConfig::class_name) ? 'courses_id' : 'classes_id';
        $totalQuery = MakeQuery::model()->countByAttributes(array($classCoursetype => $id));
        return ($totalQuery > 0) ? $totalQuery : 'No Query';
    }

    public static function makequeryafterloginuser() {
        $makequery = Yii::app()->session['make_query'];
        $model = new MakeQuery;
        $loginuserid = getLoginUserId();
        if (!empty($makequery)) {
            if (isset($makequery['MakeQuery']['classes_id']) && !empty($makequery['MakeQuery']['classes_id'])) {
                $classnames = getClaCourseInfo('Classes', $makequery['MakeQuery']['classes_id']);
                $classcoursename = $classnames->class_titile;
                $type = SkillConfig::CLASS_WORK_SHOP;
            } else {
                $type = SkillConfig::Course_WORK_SHOP;
                $classnames = getClaCourseInfo('Courses', $makequery['MakeQuery']['courses_id']);
                $classcoursename = $classnames->course_titile;
            }
            $model->setAttributes($makequery['MakeQuery']);
            $model->setAttribute('created', SkillConfig::CreateDateTime());
            if (!empty($loginuserid) && $loginuserid == $model->created_by) {
                $errorCode = Message::owan_user;
            } else {
                $email = Users::getFrontEndUser($loginuserid);
                $model->setAttribute('users_id', $loginuserid);
                $model->setAttribute('email', $email->user->username);
                $model->save(FALSE);
                unset(Yii::app()->session['make_query']);
                if (strpos($model->name, " ") !== false) {
                    $name = explode(" ", $model->name);
                    $firstname = $name[0];
                    $lastname = $name[1];
                } else {
                    $firstname = $model->name;
                    $lastname = '';
                }

                Profiles::model()->updateAll(array('first_name' => $firstname, 'last_name' => $lastname), 'user_id=:user_id', array(':user_id' => $model->users_id));
                if ($makequery['MakeQuery']['phone'] <> "" && isset($makequery['TimingMakequery']['time_from']) && isset($makequery['TimingMakequery']['time_to'])) {
                    for ($i = 0; $i < count($makequery['TimingMakequery']['time_from']); $i++) {
                        $modelTimingMakequery = new TimingMakequery;
                        $modelTimingMakequery->setAttribute('make_query_id', $model->id);
                        $modelTimingMakequery->setAttribute('time_from', $makequery['TimingMakequery']['time_from'][$i]);
                        $modelTimingMakequery->setAttribute('time_to', $makequery['TimingMakequery']['time_to'][$i]);
                        $modelTimingMakequery->save(FALSE);
                    }
                }
                Yii::app()->runController('MakeQuery/sendquerymailtoqueryusers/classcoursename/' . $classcoursename);
                Yii::app()->runController('MakeQuery/sendquerymailtotrainer/createdby/' . $model->created_by . '/firstname/' . $firstname . '/lastname/' . $lastname);
                $errorCode = Message::success;
            }
        }

        return Yii::app()->createAbsoluteUrl('makeQuery/classcoursequery', array('queryid' => $model->id, 'skillcode' => $errorCode, 'type' => $type));
    }

}